<?php
/**
 * Created by PhpStorm.
 * User: zgh
 * Date: 2022-01-20
 * Time: 14:24
 */

namespace app\common\util;

use app\common\exception\ServiceException;
use Qcloud\Cos\Client;

class TencentUploadUtil
{
    /**
     * @param $file_path
     * @param $upload_path //上传的文件路径包含有文件名
     * @throws ServiceException
     */
    public static function upload($file_path, $upload_path)
    {
        $url = "";
        if (empty($bucket = get_sysconfig("cos_bucket")) || empty($region = get_sysconfig("cos_region")) || empty($secretId = get_sysconfig("cos_secretId")) || empty($secretKey = get_sysconfig("cos_secretKey"))) {
            throw  new ServiceException("请先配置腾讯云COS配置");
        }
        $cosClient = new Client([
            "region" => $region,
            'credentials' => array(
                'secretId' => $secretId,
                'secretKey' => $secretKey)
        ]);
        $send_file = fopen($file_path, "rb");
        if ($send_file) {
            try {
                $result = $cosClient->putObject(array(
                    'Bucket' => $bucket,
                    'Key' => $upload_path,
                    'Body' => $send_file));
                if ($result && $result['Location']) {
                    $url = 'https://' . $result['Location'];
                } else {
                    throw new ServiceException("cos文件上传失败:");
                }
            } catch (\Exception $exception) {
                throw new ServiceException("cos文件上传失败:" . $exception->getMessage());
            }
        } else {
            throw  new ServiceException("cos文件上传打开失败");
        }
        return $url;
    }

}